#include "key.h"

unsigned char key_num = 0;

sbit s7 = P3^0;
sbit s6 = P3^1;
sbit s5 = P3^2;
sbit s4 = P3^3;


sbit row1 = P3^0;
sbit row2 = P3^1;
sbit row3 = P3^2;
sbit row4 = P3^3;


sbit col1 = P4^4;
sbit col2 = P4^2;
sbit col3 = P3^5;
sbit col4 = P3^4;



void ClrR(void)
{
	row1 = 0;
	row2 = 0;
	row3 = 0;
	row4 = 0;
	col1 = 1;
	col2 = 1;
	col3 = 1;
	col4 = 1;
}

void ClrC(void)
{
	row1 = 1;
	row2 = 1;
	row3 = 1;
	row4 = 1;
	col1 = 0;
	col2 = 0;
	col3 = 0;
	col4 = 0;
}

void scan_keyboard(void)
{
	static unsigned char status = 0;
	static unsigned char col = 0;
	static unsigned char mid_value = 0;
	switch(status)
	{
		case 0:
			ClrR();
			if(col1 == 0 || col2 == 0 || col3 == 0 || col4 == 0)
			{
				status = 1;
			}
			break;
		case 1:
			ClrR();
			if(col1 == 0)
			{
				status = 2;
				col = 1;
			}else if (col2 == 0){
				status = 2;
				col = 2;
			}else if (col3 == 0){
				status = 2;
				col = 3;
			}else if (col4 == 0){
				status = 2;
				col = 4;
			}else{
				status = 0;
			}
			break;
		case 2:
			ClrC();
			if(row1 == 0)
			{
				status = 3;
				mid_value = col * 4 + 3;
			}else if (row2 == 0){
				status = 3;
				mid_value = col * 4 + 2;
			}else if (row3 == 0){
				status = 3;
				mid_value = col * 4 + 1;
			}else if (row4 == 0){
				status = 3;
				mid_value = col * 4 + 0;
			}else{
				status = 0;
			}
			break;
		case 3:
			ClrC();
			if(row1 == 1 && row2 == 1 && row3 == 1 && row4 == 1)
			{
				status = 0;
				key_num = mid_value;
			}
	}


}


















void clean_all(void)
{
	s4 = 1;
	s5 = 1;
	s6 = 1;
	s7 = 1;
}
void indep_key(void)
{
	static unsigned char status = 0;
	static unsigned char key_temp = 0;
	switch(status)
	{
		case 0:
			clean_all();
			if(s4 == 0 || s5 == 0 || s6 == 0 || s7 == 0)
			{
				status = 1;
			}
			break;
			
		case 1:
			clean_all();
			if(s4 == 0){
				status = 2;
				key_temp = 4;
			}else if(s5 == 0){
				status = 2;
				key_temp = 5;
			}else if(s6 == 0){
				status = 2;
				key_temp = 6;
			}else if(s7 == 0){
				status = 2;
				key_temp = 7;
			}else{
				status = 0;
			}
			break;
			
		case 2:
			clean_all();
			if(s4 == 1 && s5 == 1 && s6 == 1 && s7 == 1)
			{
				status = 0;
				key_num = key_temp;
			}
			break;
	}
}

